import { app, dialog } from 'electron';
import fs from 'fs';
import path from 'path';
import { title } from 'process';

// 获取用户的配置文件路径
const getUserDataPath = () => {
    return app.getPath('userData');
};
// 获取安装目录路径
const getInstallPath = () => {
    return app.getPath('exe');
}

// 读取配置文件
const readConfig = () => {
    const userDataPath = getUserDataPath();
    const configPath = path.join(userDataPath, 'config.json');

    try {
        const content = fs.readFileSync(configPath, 'utf-8');
        return JSON.parse(content);
    } catch (err) {
        return null; // 如果文件不存在或读取失败，返回一个空对象
    }
};

// 写入配置文件
const writeConfig = (config) => {
    const userDataPath = getUserDataPath();
    const configPath = path.join(userDataPath, 'config.json');
    try {
        fs.writeFileSync(configPath, JSON.stringify(config), 'utf-8');
    } catch (err) {
        console.error('写入配置文件失败:', err);
    }
};

// 读取绝对路径文件
const readFile = (path) => {
    try {
        return fs.readFileSync(path, 'utf-8');
    } catch (err) {
        console.error('读取文件失败:', err);
    }
};
// 读取TodoList
const readTodoList = () => {
    const userDataPath = getUserDataPath();
    const todoListPath = path.join(userDataPath, 'todoList.json');

    try {
        const content = fs.readFileSync(todoListPath, 'utf-8');
        return JSON.parse(content);
    } catch (err) {
        return null; // 如果文件不存在或读取失败，返回一个空对象
    }
}
// 写入TodoList
const writeTodoList = (todoList) => {
    const userDataPath = getUserDataPath();
    const todoListPath = path.join(userDataPath, 'todoList.json');
    // const options = {
    //     title: 'save files',
    //     defaultPath: 'todoList',
    //     buttonLabel: 'Save',
    //     filters: [{ name: 'JSON', extensions: ['json'] }, { name: 'All Files', extensions: ['*'] }],
    // }
    // dialog.showSaveDialog(null, options).then((result) => {
    //     console.log('filePath', result);
    //     if (result.filePath) {
    //         try {
    //             fs.writeFileSync(result.filePath, JSON.stringify(todoList), 'utf-8');
    //         } catch (err) {
    //             console.error('写入TodoList失败:', err);
    //         }
    //     }
    // })
    try {
        fs.writeFileSync(todoListPath, JSON.stringify(todoList), 'utf-8');
    } catch (err) {
        console.error('写入TodoList失败:', err);
    }

}
// 读取书籍配置
const readBookConfig = () => {
    const userDataPath = getUserDataPath();
    const bookConfigPath = path.join(userDataPath, 'bookConfig.json');

    try {
        const content = fs.readFileSync(bookConfigPath, 'utf-8');
        return JSON.parse(content);
    } catch (err) {
        return null; // 如果文件不存在或读取失败，返回一个空对象
    }
}
// 写入书籍配置
const writeBookConfig = (bookConfig) => {
    const userDataPath = getUserDataPath();
    const bookConfigPath = path.join(userDataPath, 'bookConfig.json');
    try {
        fs.writeFileSync(bookConfigPath, JSON.stringify(bookConfig), 'utf-8');
    } catch (err) {
        console.error('写入书籍配置失败:', err);
    }
}
// 根据‘第’“章”到'换行符'获取章节名称和章节内容,返回指定索引的章节内容和章节名称，章节总数
// const getSection = (bookData, index) => {
//     // 章节名称是"第xx章"到“换行符”
//     const sections = bookData.match(/第\d+章[\s\S]*?(?=\n|$)/g);
//     // 章节内容是"第xx章"到“换行符”之后的内容到下一个第xx章，如果没有下一个第xx章，则到文件末尾
//     const sectionContents = bookData.match(/第\d+章[\s\S]*?(?=\n第\d+章|$)/g);
//     console.log('sections',sections.length);
//     console.log('sectionContents',sectionContents.length);
//     if (sections && sectionContents) {
//         const sectionName = sections[index];
//         const sectionContent = sectionContents[index];
//         return { sectionName, sectionContent, total: sections.length };
//     } else {
//         const sectionName = '解析目录失败，展示全部内容。'
//         const sectionContent = bookData;
//         return { sectionName, sectionContent, total: 1 };
//     }
// }
const getSection = (bookData, index) => {
    // 章节名称是"第xx章"到“换行符”
    const sections = bookData.match(/第\d+章[\s\S]*?(?=\n|$)/g);
    if (!sections) {
        const sectionName = '解析目录失败，展示全部内容。';
        const sectionContent = bookData;
        return { sectionName, sectionContent, total: 1 };
    }

    // 章节内容是"第xx章"到“换行符”之后的内容到下一个第xx章，如果没有下一个第xx章，则到文件末尾
    const sectionContents = [];
    for (let i = 0; i < sections.length; i++) {
        const start = bookData.indexOf(sections[i]) + sections[i].length;
        const nextSectionIndex = bookData.indexOf(sections[i + 1]);
        const end = nextSectionIndex !== -1 ? nextSectionIndex : bookData.length;
        const sectionContent = bookData.substring(start, end).trim();
        sectionContents.push(sectionContent);
    }

    if (sectionContents[index]) {
        const sectionName = sections[index];
        const sectionContent = sectionContents[index];
        return { sectionName, sectionContent, total: sections.length };
    } else {
        const sectionName = '解析目录失败，展示全部内容。';
        const sectionContent = bookData;
        return { sectionName, sectionContent, total: 1 };
    }
};
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 读取歌单配置
const readMusicConfig = () => {
    const userDataPath = getUserDataPath();
    const musicConfigPath = path.join(userDataPath, 'musicConfig.json');

    try {
        const list = JSON.parse(fs.readFileSync(musicConfigPath, 'utf-8'));
        let res = list.map(song => {
            try {
                const buffer = fs.readFileSync(song.url);
                return {
                    ...song,
                    url: buffer.toString('base64'), // 将 buffer 转换为 base64 字符串,
                };
            } catch (err) {
                console.error(`读取文件 ${song.path} 失败:`, err.message);
                return {
                    ...song,
                    url: null,
                };
            }
        })
        return res;
    } catch (err) {
        console.log('err',err);
        return []; // 如果文件不存在或读取失败，返回一个空数组
    }
}
// 写入歌单配置
const writeMusicConfig = (musicConfig) => {
    const userDataPath = getUserDataPath();
    const musicConfigPath = path.join(userDataPath, 'musicConfig.json');
    try {
        fs.writeFileSync(musicConfigPath, JSON.stringify(musicConfig), 'utf-8');
    } catch (err) {
        console.error('写入书籍配置失败:', err);
    }
}

export { 
    readConfig, 
    writeConfig, 
    readFile, 
    readTodoList, 
    writeTodoList, 
    readBookConfig, 
    writeBookConfig, 
    getSection,
    formatDate,
    readMusicConfig,
    writeMusicConfig
};